from rest_framework import serializers
from decimal import Decimal
import logging, datetime, json
from geopy.distance import geodesic

from users.models import CustomerUser, Level, CustomerUserAddress
from vouchers.models import *
from orders.models import *
from goods.models import *
from activities.models import *
from equity_mall.utils.sync_img_to_local import make_qrcode1
from equity_mall.utils.utils import random_str
from speeds.models import *
from merchants.models import MerchantBill, Merchant
from equity_mall.utils.synchronous_coupons_status import synchronous_wx_coupons_status
from cashbonus.models import *
from customers.models import *

logger = logging.getLogger('django')


class UserInfoModelSerializer(serializers.ModelSerializer):

    is_auth_str = serializers.CharField(source='get_is_auth_display', read_only=True)
    identification_type_str = serializers.CharField(source='get_identification_type_display', read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    idcode = serializers.SerializerMethodField(read_only=True)
    realname = serializers.SerializerMethodField(read_only=True)
    point = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomerUser
        fields = ('id', 'username', 'mobile', 'point', 'avatar', 'is_auth', 'is_auth_str', 'idcode', 'realname', 'is_psbc_card',
                  'identification_type', 'identification_type_str')

    def get_point(self, obj):
        try:
            point = str(int(obj.point))
            if len(point) >= 3:
                return f'{point[:-2]},{point[-2:]}'
            else:
                return point
        except:
            return '0'

    def get_mobile(self, obj):
        try:
            return f'{obj.mobile[:3]}******{obj.mobile[-2:]}'
        except:
            return ''

    def get_idcode(self, obj):
        try:
            return f'{obj.idcode[:1]}****************{obj.idcode[-1:]}'
        except:
            return ''

    def get_realname(self, obj):
        try:
            return f'{(len(obj.realname)-1) * "*"}{obj.realname[-1:]}'
        except:
            return ''


class OrderGoodsSerializer(serializers.ModelSerializer):

    default_image = serializers.SerializerMethodField(read_only=True)
    name = serializers.SerializerMethodField(read_only=True)
    merchant_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderGoods
        fields = ('id', 'default_image', 'count', 'price', 'name', 'merchant_name', 'goods_id')

    def get_default_image(self, obj):
        try:
            return obj.goods.default_image.url
        except Exception as e:
            logger.error(e)
            return ''

    def get_name(self, obj):
        try:
            return obj.goods.name
        except Exception as e:
            logger.error(e)
            return ''

    def get_merchant_name(self, obj):
        try:
            return obj.goods.merchant.name
        except Exception as e:
            logger.error(e)
            return ''


class OrderInfoListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    order_type_str = serializers.CharField(source='get_order_type_display', read_only=True)
    ordergoods_set = OrderGoodsSerializer(many=True)
    merchant_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderInfo
        fields = ['id', 'create_time', 'order_id', 'state', 'state_str', 'ordergoods_set', 'total_price', 'merchant_name', 'order_type',
                  'order_type_str']

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except Exception as e:
            logger.error(e)
            return ''


class GoodsCouponsModelSerializer(serializers.ModelSerializer):

    status_str = serializers.CharField(source='get_status_display', read_only=True)
    coupons_qrcode = serializers.SerializerMethodField(read_only=True)
    validity_time = serializers.SerializerMethodField(read_only=True)
    coupons_id_off = serializers.SerializerMethodField(read_only=True)
    # validity_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = GoodsCoupons
        fields = ['id', 'validity_time', 'status_str', 'status', 'coupons_id', 'coupons_qrcode', 'coupons_id_off']

    def get_coupons_id_off(self, obj):
        try:
            coupons_id = obj.coupons_id
            return f'{coupons_id[:4]}****{coupons_id[-3:]}'
        except:
            return ''

    def get_validity_time(self, obj):
        try:
            if obj.goods_id in [1008211, 1008210, 1008212, 1008213, 10199146]:
                if obj.status == 1:
                    if obj.validity_time < datetime.datetime.now():
                        obj.status = 3
                        obj.save()
                return obj.validity_time.strftime("%Y-%m-%d %H:%M:%S")
            else:
                return ''
        except:
            return ''

    def get_coupons_qrcode(self, obj):
        try:
            instance = GoodsCoupons.objects.get(id=obj.id)
            if not instance.coupons_qrcode:
                identify = random_str()
                coupon_qrcode = f'youhuiquanyi/goodscoupon/goodscoupon_{instance.goods_id}/{identify}.png'
                coupon_qrcode_url = make_qrcode1(identify, obj.coupons_id, coupon_qrcode)
                instance.coupons_qrcode = coupon_qrcode
                instance.save()
                instance = GoodsCoupons.objects.get(id=obj.id)
            return instance.coupons_qrcode.url
        except Exception as e:
            return ''


class VoucherDetailModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = VoucherDetail
        fields = ['id', 'amount', 'name', 'voucherId']


class OrderFundTransSerializer(serializers.ModelSerializer):

    status_str = serializers.SerializerMethodField(read_only=True)
    trans_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_reason = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderFundTrans
        fields = ['id', 'pay_fund_order_id', 'exchange_amount', 'name', 'status', 'status_str',
                  'trans_date', 'status_reason', 'identity']

    def get_status_str(self, obj):
        try:
            if obj.status == 2:
                return '交易成功'
            else:
                return f'交易失败'
        except:
            return ''

    def get_status_reason(self, obj):
        try:
            if obj.status == 2:
                return '请使用上述账户登录支付宝APP，点击【我的】-【余额】-【余额变动明细】查询。'
            else:
                return f'{obj.sub_msg}。具体请联系客户经理修改收款信息.'
        except:
            return ''


class OrderInfoRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    cancel_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    ordergoods_set = OrderGoodsSerializer(many=True)
    customer_user = serializers.SerializerMethodField(read_only=True)
    goodscoupons_set = GoodsCouponsModelSerializer(many=True)
    voucherdetail_set = VoucherDetailModelSerializer(many=True)
    merchant_name = serializers.SerializerMethodField(read_only=True)
    discount_amount = serializers.SerializerMethodField(read_only=True)
    realpay_amount = serializers.SerializerMethodField(read_only=True)
    order_type_str = serializers.CharField(source='get_order_type_display', read_only=True)
    orderfundtrans_set = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    total_point = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderInfo
        fields = ['id', 'create_time', 'order_id', 'state', 'state_str', 'ordergoods_set', 'total_price', 'customer_user', 'goodscoupons_set', 'voucherdetail_set',
                  'merchant_name', 'payment_time', 'cancel_time', 'realpay_amount', 'discount_amount', 'order_type_str', 'order_type',
                  'orderfundtrans_set', 'level', 'total_point']

    def get_total_point(self, obj):
        try:
            return obj.total_point / 100
        except:
            return 0

    def get_orderfundtrans_set(self, obj):
        try:
            orderfundtrans_set = obj.orderfundtrans_set.exclude(status=1)
            return OrderFundTransSerializer(orderfundtrans_set, many=True).data
        except:
            return []

    def get_level(self, obj):
        data = {}
        data['name'] = ''
        data['longitude'] = ''
        data['latitude'] = ''
        data['address'] = ''
        data['telephone'] = ''
        data['city_id'] = ''
        data['work_time'] = ''
        data['id'] = ''
        try:
            level = obj.level
            if level:
                if obj.order_type in [1, 4]:
                    data['name'] = level.name
                data['longitude'] = level.longitude
                data['latitude'] = level.latitude
                data['address'] = level.address
                data['telephone'] = level.telephone
                data['city_id'] = level.city_id
                data['work_time'] = level.work_time
                data['id'] = level.id
        except:
            pass
        return data

    def get_customer_user(self, obj):
        data = {}
        data['realname'] = ''
        data['mobile'] = ''
        try:
            customer_user = obj.customer_user
            data['realname'] = customer_user.realname
            data['mobile'] = customer_user.mobile
            return data
        except Exception as e:
            logger.error(e)
        return data

    def get_discount_amount(self, obj):
        try:
            if obj.state in [12, 2, 3, 9, 6, 8, 5, 14]:
                return str(Decimal(obj.total_price - obj.realpay_amount).quantize(Decimal('0.00')))
            elif obj.state == 1:
                return str(Decimal(obj.total_price - obj.payable_amount).quantize(Decimal('0.00')))
            else:
                return '0.00'
        except Exception as e:
            logger.error(e)
        return '0.00'

    def get_realpay_amount(self, obj):
        try:
            if obj.state == 1:
                return obj.payable_amount
            else:
                return obj.realpay_amount
        except Exception as e:
            logger.error(e)
        return '0.00'

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except Exception as e:
            logger.error(e)
            return ''


class AliDiscountCouponInfoListModelSerializer(serializers.ModelSerializer):

    gmt_create = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_expired = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    floor_amount = serializers.SerializerMethodField(read_only=True)
    amount = serializers.SerializerMethodField(read_only=True)
    coupon_channel = serializers.SerializerMethodField(read_only=True)
    is_need_auth = serializers.SerializerMethodField(read_only=True)
    coupon_type = serializers.SerializerMethodField(read_only=True)
    activity_description = serializers.SerializerMethodField(read_only=True)
    coupon_type_str = serializers.SerializerMethodField(read_only=True)
    status = serializers.SerializerMethodField(read_only=True)
    is_couponbag = serializers.SerializerMethodField(read_only=True)
    usage_scenario_str = serializers.SerializerMethodField(read_only=True)
    contentLink = serializers.SerializerMethodField(read_only=True)
    is_use_path = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponInfo
        fields = ['id', 'gmt_create', 'mobile', 'status', 'status_str', 'gmt_expired', 'activity_name',
                  'floor_amount', 'amount', 'alidiscountcoupon_id', 'coupon_channel', 'is_need_auth', 'voucher_id', 'coupon_type',
                  'activity_description', 'coupon_type_str', 'order_id', 'return_msg', 'is_couponbag', 'usage_scenario_str',
                  'contentLink', 'is_use_path']

    def get_is_couponbag(self, obj):
        try:
            check_detail = CustomizeActivityFlipCARDSDetail.objects.filter(alidiscountcouponinfo_id=obj.id)
            if check_detail:
                return 1
            else:
                return 0
        except:
            return 0

    def get_status(self, obj):
        try:
            if obj.status == 1:
                date_now = datetime.datetime.now()
                if obj.gmt_expired < date_now:
                    obj.status = 12
                    obj.save()
            return obj.status
        except:
            return obj.status

    def get_coupon_type(self, obj):
        try:
            return obj.alidiscountcoupon.coupon_type
        except:
            return ''

    def get_coupon_type_str(self, obj):
        try:
            return obj.alidiscountcoupon.get_coupon_type_display()
        except:
            return ''

    def get_usage_scenario_str(self, obj):
        try:
            if obj.alidiscountcoupon.usage_scenario:
                return obj.alidiscountcoupon.get_usage_scenario_display()
            else:
                return '指定商户可用'
        except:
            return ''

    def get_activity_description(self, obj):
        try:
            return obj.alidiscountcoupon.activity_description
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.alidiscountcoupon.activity_name
        except:
            return ''

    def get_is_need_auth(self, obj):
        try:
            return obj.alidiscountcoupon.is_need_auth
        except:
            return 0

    def get_coupon_channel(self, obj):
        try:
            return obj.alidiscountcoupon.coupon_channel
        except:
            return ''

    def get_floor_amount(self, obj):
        try:
            return obj.alidiscountcoupon.floor_amount
        except:
            return ''

    def get_amount(self, obj):
        try:
            if obj.alidiscountcoupon.coupon_type != 6:
                return obj.alidiscountcoupon.amount
            else:
                return '单品券'
        except:
            return ''

    def get_contentLink(self, obj):
        contentLink = {
            "path": '',
            "appid": '',
            "is_self": ''
        }
        try:
            if obj.status == 1 and obj.alidiscountcoupon.is_use_path == 1:
                contentLink['path'] = obj.alidiscountcoupon.use_path + f"?coupon_id={obj.voucher_id}"
                contentLink['appid'] = obj.alidiscountcoupon.use_appid
                contentLink['is_self'] = obj.alidiscountcoupon.is_self
        except:
            pass
        return contentLink

    def get_is_use_path(self, obj):
        try:
            if obj.status == 1 and obj.alidiscountcoupon.is_use_path == 1:
                return 1
            else:
                return 0
        except:
            return 0


class AliDiscountCouponInfoRetrieveModelSerializer(serializers.ModelSerializer):

    gmt_create = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_use = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_expired = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_undo = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_active = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    floor_amount = serializers.SerializerMethodField(read_only=True)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    companyuser_nickname = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    coupon_channel = serializers.SerializerMethodField(read_only=True)
    activity_description = serializers.SerializerMethodField(read_only=True)
    usage_scenario_str = serializers.SerializerMethodField(read_only=True)
    contentLink = serializers.SerializerMethodField(read_only=True)
    is_use_path = serializers.SerializerMethodField(read_only=True)
    amount = serializers.SerializerMethodField(read_only=True)
    coupon_type = serializers.SerializerMethodField(read_only=True)
    coupon_type_str = serializers.SerializerMethodField(read_only=True)
    is_need_auth = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponInfo
        fields = ['id', 'gmt_create', 'mobile', 'status', 'status_str', 'floor_amount', 'companyuser_nickname',
                  'activity_name', 'gmt_use', 'gmt_expired', 'gmt_undo', 'alidiscountcoupon_id', 'coupon_channel',
                  'activity_description', 'gmt_active', 'usage_scenario_str',
                  'contentLink', 'is_use_path', 'amount', 'coupon_type', 'coupon_type_str', 'is_need_auth']

    def get_usage_scenario_str(self, obj):
        try:
            if obj.alidiscountcoupon.usage_scenario:
                return obj.alidiscountcoupon.get_usage_scenario_display()
            else:
                return '指定商户可用'
        except:
            return ''

    def get_floor_amount(self, obj):
        try:
            return obj.alidiscountcoupon.floor_amount
        except:
            return ''

    def get_activity_description(self, obj):
        try:
            return obj.alidiscountcoupon.activity_description
        except:
            return ''

    def get_coupon_channel(self, obj):
        try:
            return obj.alidiscountcoupon.coupon_channel
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.alidiscountcoupon.activity_name
        except:
            return ''

    def get_companyuser_nickname(self, obj):
        try:
            return obj.companyuser.nickname
        except:
            return ''

    def get_contentLink(self, obj):
        contentLink = {
            "path": '',
            "appid": '',
            "is_self": ''
        }
        try:
            if obj.status == 1 and obj.alidiscountcoupon.is_use_path == 1:
                contentLink['path'] = obj.alidiscountcoupon.use_path + f"?coupon_id={obj.voucher_id}"
                contentLink['appid'] = obj.alidiscountcoupon.use_appid
                contentLink['is_self'] = obj.alidiscountcoupon.is_self
        except:
            pass
        return contentLink

    def get_is_use_path(self, obj):
        try:
            if obj.status == 1 and obj.alidiscountcoupon.is_use_path == 1:
                return 1
            else:
                return 0
        except:
            return 0

    def get_amount(self, obj):
        try:
            if obj.alidiscountcoupon.coupon_type != 6:
                return obj.alidiscountcoupon.amount
            else:
                return '单品券'
        except:
            return ''

    def get_coupon_type(self, obj):
        try:
            return obj.alidiscountcoupon.coupon_type
        except:
            return ''

    def get_coupon_type_str(self, obj):
        try:
            return obj.alidiscountcoupon.get_coupon_type_display()
        except:
            return ''

    def get_is_need_auth(self, obj):
        try:
            return obj.alidiscountcoupon.is_need_auth
        except:
            return 0


class GoodsListModelSerializer(serializers.ModelSerializer):

    merchant_name = serializers.SerializerMethodField(read_only=True)
    stock = serializers.SerializerMethodField(read_only=True)
    order_type_str = serializers.CharField(source='get_order_type_display', read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'price', 'merchant_name', 'sales', 'default_image', 'name', 'stock',
                  'order_type', 'order_type_str')

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except:
            return ''

    def get_stock(self, obj):
        level_id = self.context.get('level_id', None)
        if level_id:
            try:
                launchedgoods = LaunchedGoods.objects.filter(level_id=level_id, goods_id=obj.id).first()
                if launchedgoods:
                    return launchedgoods.stock
                else:
                    return 0
            except:
                return obj.remain_stock
        else:
            return obj.remain_stock


class GoodsRetrieveModelSerializer(serializers.ModelSerializer):

    merchant_name = serializers.SerializerMethodField(read_only=True)
    goodsimage_set = serializers.SerializerMethodField(read_only=True)
    desc_detail = serializers.SerializerMethodField(read_only=True)
    stock = serializers.SerializerMethodField(read_only=True)
    order_type_str = serializers.CharField(source='get_order_type_display', read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'price', 'merchant_name', 'sales', 'default_image', 'goodsimage_set', 'desc_detail', 'name', 'market_price', 'stock',
                  'order_type', 'order_type_str', 'is_buymore', 'merchant_id')

    def get_desc_detail(self, obj):
        try:
            return json.loads(obj.desc_detail)
        except:
            return obj.desc_detail

    def get_goodsimage_set(self, obj):
        data = []
        try:
            goodsimage_set = obj.goodsimage_set.all()
            for goodsimage in goodsimage_set:
                data.append(goodsimage.image.url)
        except:
            pass
        return data

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.short_name
        except:
            return ''

    def get_stock(self, obj):
        level_id = self.context.get('level_id', None)
        if level_id:
            try:
                launchedgoods = LaunchedGoods.objects.filter(level_id=level_id, goods_id=obj.id).first()
                if launchedgoods:
                    return launchedgoods.stock
                else:
                    return 0
            except:
                return obj.remain_stock
        else:
            return obj.remain_stock


class LaunchedGoodsListModelSerializer(serializers.ModelSerializer):

    merchant_name = serializers.SerializerMethodField(read_only=True)
    default_image = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = LaunchedGoods
        fields = ('id', 'price', 'merchant_name', 'sales', 'default_image', 'name', 'stock', 'is_default', 'level_id')

    def get_merchant_name(self, obj):
        try:
            return obj.goods.merchant.name
        except:
            return ''

    def get_default_image(self, obj):
        try:
            return obj.goods.default_image.url
        except:
            return ''


class LaunchedGoodsRetrieveModelSerializer(serializers.ModelSerializer):

    merchant_name = serializers.SerializerMethodField(read_only=True)
    goodsimage_set = serializers.SerializerMethodField(read_only=True)
    desc_detail = serializers.SerializerMethodField(read_only=True)
    market_price = serializers.SerializerMethodField(read_only=True)
    default_image = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = LaunchedGoods
        fields = ('id', 'price', 'merchant_name', 'sales', 'default_image', 'goodsimage_set', 'desc_detail', 'name', 'market_price', 'stock')

    def get_market_price(self, obj):
        try:
            return obj.goods.market_price
        except:
            return ''

    def get_default_image(self, obj):
        try:
            return obj.goods.default_image.url
        except:
            return ''

    def get_desc_detail(self, obj):
        try:
            return json.loads(obj.goods.desc_detail)
        except:
            return obj.goods.desc_detail

    def get_goodsimage_set(self, obj):
        data = []
        try:
            goodsimage_set = obj.goods.goodsimage_set.all()
            for goodsimage in goodsimage_set:
                data.append(goodsimage.image.url)
        except:
            pass
        return data

    def get_merchant_name(self, obj):
        try:
            return obj.goods.merchant.name
        except:
            return ''


class SpeedLoanIndustryModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = SpeedLoanIndustry
        fields = ('id', 'name')


class SpeedLoanDrawModelSerializer(serializers.ModelSerializer):

    payment_status_str = serializers.CharField(source='get_payment_status_display', read_only=True)

    class Meta:
        model = SpeedLoanDraw
        fields = ('id', 'amount', 'payment_status', 'payment_status_str', 'gears')


class LevelModelSerializer(serializers.ModelSerializer):

    distance = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Level
        fields = ['id', 'name', 'longitude', 'latitude', 'address', 'distance', 'telephone', 'city_id', 'work_time']

    def get_distance(self, obj):
        longitude = self.context.get('longitude', None)
        latitude = self.context.get('latitude', None)
        if longitude and latitude:
            try:
                distance = geodesic((obj.latitude, obj.longitude), (latitude, longitude)).m
                if distance > 1000:
                    return f'{round(distance/1000, 1)} km'
                else:
                    return f'{int(distance)} m'
            except:
                return ''
        else:
            return ''


class MerchantListModelSerializer(serializers.ModelSerializer):

    distance = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Merchant
        fields = ['id', 'name', 'distance', 'store_address', 'longitude', 'latitude', 'store_header_copy', 'managermobile', 'store_logo_copy', 'short_name']

    def get_distance(self, obj):
        longitude = self.context.get('longitude', None)
        latitude = self.context.get('latitude', None)
        if longitude and latitude:
            try:
                distance = geodesic((obj.latitude, obj.longitude), (latitude, longitude)).m
                if distance > 1000:
                    return f'{round(distance/1000, 1)} km'
                else:
                    return f'{int(distance)} m'
            except:
                return ''
        else:
            return ''


class MerchantRetrieveModelSerializer(serializers.ModelSerializer):

    open_work_time = serializers.DateTimeField(format="%H:%M", required=False)
    close_work_time = serializers.DateTimeField(format="%H:%M", required=False)
    merchantimage_set = serializers.SerializerMethodField(read_only=True)
    region = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Merchant
        fields = ['id', 'name', 'short_name', 'managerName', 'merchant_desc', 'close_work_time', 'open_work_time', 'merchantimage_set', 'managermobile', 'store_address', 'longitude', 'latitude',
                  'region']

    def get_merchantimage_set(self, obj):
        data = []
        try:
            # Merchant.objects.all()
            merchantimage_set = obj.merchantimage_set.all()
            for merchantimage in merchantimage_set:
                data.append(merchantimage.image.url)
        except:
            pass
        return data

    def get_region(self, obj):
        data = []
        try:
            if obj.prov_name:
                data.append(obj.prov_name)
                data.append(obj.city_name)
                data.append(obj.district_name)
        except:
            pass
        return data


class AliDiscountCouponModelSerializer(serializers.ModelSerializer):

    state = serializers.SerializerMethodField(read_only=True)
    publish_end_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    publish_start_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    coupon_type_str = serializers.CharField(source='get_coupon_type_display', read_only=True)
    usetime_type = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCoupon
        fields = ['id', 'activity_name', 'amount', 'transaction_minimum', 'floor_amount', 'state', 'activity_description',
                  'publish_start_time', 'publish_end_time', 'coupon_type_str', 'coupon_channel', 'available_merchants', 'usetime_type']

    def get_usetime_type(self, obj):
        try:
            if obj.coupon_type in [2, 6, 8]:
                channelcommonvoucher = obj.alidiscountcouponchannelcommonvoucher
                if channelcommonvoucher.usetime_type == 2:
                    return f'{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
                elif channelcommonvoucher.usetime_type == 3:
                    return f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
                else:
                    return f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
            else:
                return ''
        except:
            return ''

    def get_state(self, obj):
        user = self.context.get('user', None)
        if not user:
            return 1
        else:
            try:
                query = AliDiscountCouponInfo.objects.filter(customer_user_id=user.id, alidiscountcoupon_id=obj.id)
                if 1 in query.values_list('status', flat=True):
                    try:
                        id_list = query.filter(status=1).values_list('id', flat=True)
                        synchronous_wx_coupons_status(list(id_list))
                        query2 = AliDiscountCouponInfo.objects.filter(customer_user_id=user.id, alidiscountcoupon_id=obj.id)
                        if 1 in query2.values_list('status', flat=True):
                            return 2
                        elif obj.max_number_by_user > query2.count():
                            return 1
                        else:
                            return 2
                    except:
                        pass
                    return 2
                elif obj.max_number_by_user > query.count():
                    return 1
                else:
                    return 2
            except:
                return 1


class AliDiscountCouponLimitModelSerializer(serializers.ModelSerializer):

    state = serializers.SerializerMethodField(read_only=True)
    publish_end_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    publish_start_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    coupon_type_str = serializers.CharField(source='get_coupon_type_display', read_only=True)
    coupon_status = serializers.SerializerMethodField(read_only=True)
    usetime_type = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCoupon
        fields = ['id', 'activity_name', 'amount', 'transaction_minimum', 'floor_amount', 'state', 'activity_description',
                  'publish_start_time', 'publish_end_time', 'coupon_type_str', 'coupon_channel', 'coupon_status', 'available_merchants',
                  'usetime_type']

    def get_usetime_type(self, obj):
        try:
            if obj.coupon_type in [2, 6, 8]:
                channelcommonvoucher = obj.alidiscountcouponchannelcommonvoucher
                if channelcommonvoucher.usetime_type == 2:
                    return f'{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
                elif channelcommonvoucher.usetime_type == 3:
                    return f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
                else:
                    return f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
            else:
                return ''
        except:
            return ''

    def get_coupon_status(self, obj):
        data = {}
        data['status'] = obj.coupon_status
        date_now = datetime.datetime.now()
        week = date_now.weekday()
        week_dict = {
            6: 5,
            0: 4,
            1: 3,
            2: 2,
            3: 1,
            4: 0,
            5: 6
        }
        data['time'] = date_now.strftime('%Y-%m-%d %H:%M:%S')
        publish_time = date_now + datetime.timedelta(days=week_dict[week])
        start_enable_time = obj.start_enable_time.strftime(' %H:%M:%S')
        publish_start_time = datetime.datetime.strptime(publish_time.strftime('%Y-%m-%d') + start_enable_time, '%Y-%m-%d %H:%M:%S')
        publish_end_time = publish_time.strftime('%Y-%m-%d 23:59:59')
        try:
            if publish_start_time >= date_now:
                data['status'] = 0
                data['time'] = publish_start_time.strftime('%Y-%m-%d %H:%M:%S')
            else:
                data['status'] = 1
                data['time'] = publish_end_time
        except:
            pass
        return data

    def get_state(self, obj):
        user = self.context.get('user', None)
        if not user:
            return 1
        else:
            try:
                query = AliDiscountCouponInfo.objects.filter(customer_user_id=user.id, alidiscountcoupon_id=obj.id)
                if 1 in query.values_list('status', flat=True):
                    try:
                        id_list = query.filter(status=1).values_list('id', flat=True)
                        synchronous_wx_coupons_status(list(id_list))
                        query2 = AliDiscountCouponInfo.objects.filter(customer_user_id=user.id, alidiscountcoupon_id=obj.id)
                        if 1 in query2.values_list('status', flat=True):
                            return 2
                        elif obj.max_number_by_user > query2.count():
                            return 1
                        else:
                            return 2
                    except:
                        pass
                    return 2
                elif obj.max_number_by_user > query.count():
                    return 1
                else:
                    return 2
            except:
                return 1


class AliDiscountCouponMapModelSerializer(serializers.ModelSerializer):

    state = serializers.SerializerMethodField(read_only=True)
    publish_end_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    publish_start_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    coupon_type_str = serializers.CharField(source='get_coupon_type_display', read_only=True)
    coupon_status = serializers.SerializerMethodField(read_only=True)
    usetime_type = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCoupon
        fields = ['id', 'activity_name', 'amount', 'transaction_minimum', 'floor_amount', 'state', 'activity_description',
                  'publish_start_time', 'publish_end_time', 'coupon_type_str', 'coupon_channel', 'coupon_status', 'available_merchants',
                  'usetime_type', 'coupon_way', 'coupon_channel']

    def get_usetime_type(self, obj):
        try:
            if obj.coupon_type in [2, 6, 8]:
                channelcommonvoucher = obj.alidiscountcouponchannelcommonvoucher
                if channelcommonvoucher.usetime_type == 2:
                    return f'{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
                elif channelcommonvoucher.usetime_type == 3:
                    return f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
                else:
                    return f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
            else:
                return ''
        except:
            return ''

    def get_coupon_status(self, obj):
        data = {}
        data['status'] = ''
        data['time'] = ''
        if obj.coupon_way == 3:
            data['status'] = obj.coupon_status
            date_now = datetime.datetime.now()
            week = date_now.weekday()
            week_dict = {
                6: 5,
                0: 4,
                1: 3,
                2: 2,
                3: 1,
                4: 0,
                5: 6
            }
            data['time'] = date_now.strftime('%Y-%m-%d %H:%M:%S')
            publish_time = date_now + datetime.timedelta(days=week_dict[week])
            publish_start_time = datetime.datetime.strptime(publish_time.strftime('%Y-%m-%d 09:00:00'), '%Y-%m-%d %H:%M:%S')
            publish_end_time = publish_time.strftime('%Y-%m-%d 23:59:59')
            try:
                if publish_start_time >= date_now:
                    data['status'] = 0
                    data['time'] = publish_start_time.strftime('%Y-%m-%d %H:%M:%S')
                else:
                    data['status'] = 1
                    data['time'] = publish_end_time
            except:
                pass
        return data

    def get_state(self, obj):
        user = self.context.get('user', None)
        if not user:
            return 1
        else:
            try:
                query = AliDiscountCouponInfo.objects.filter(customer_user_id=user.id, alidiscountcoupon_id=obj.id)
                if 1 in query.values_list('status', flat=True):
                    try:
                        id_list = query.filter(status=1).values_list('id', flat=True)
                        synchronous_wx_coupons_status(list(id_list))
                        query2 = AliDiscountCouponInfo.objects.filter(customer_user_id=user.id, alidiscountcoupon_id=obj.id)
                        if 1 in query2.values_list('status', flat=True):
                            return 2
                        elif obj.max_number_by_user > query2.count():
                            return 1
                        else:
                            return 2
                    except:
                        pass
                    return 2
                elif obj.max_number_by_user > query.count():
                    return 1
                else:
                    return 2
            except:
                return 1


class GoodsCategoryModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = GoodsCategory
        fields = ['id', 'name', 'icon']


class ActivityDataListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    point = serializers.SerializerMethodField(read_only=True)
    remain_point = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    available_time = serializers.SerializerMethodField(read_only=True)
    amount = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ActivityData
        fields = ['id', 'create_time', 'state_str', 'state', 'point', 'activity_name', 'available_time', 'remain_point', 'amount']

    def get_point(self, obj):
        try:
            point = str(int(obj.point))
            if len(point) >= 3:
                return f'{point[:-2]},{point[-2:]}'
            else:
                return point
        except:
            return '0'

    def get_remain_point(self, obj):
        try:
            remain_point = str(int(obj.remain_point))
            if len(remain_point) >= 3:
                return f'{remain_point[:-2]},{remain_point[-2:]}'
            else:
                return remain_point
        except:
            return '0'

    def get_amount(self, obj):
        try:
            return obj.remain_point / Decimal('100')
        except:
            return '0'

    def get_activity_name(self, obj):
        try:
            return obj.activity.name
        except:
            return ''

    def get_available_time(self, obj):
        try:
            activity = obj.activity
            return f'{activity.available_end_time.strftime("%Y/%m/%d %H:%M:%S")}'
        except:
            return ''


class PointRecordModelSerializer(serializers.ModelSerializer):

    point = serializers.SerializerMethodField(read_only=True)
    remain_point = serializers.SerializerMethodField(read_only=True)
    title = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y/%m/%d %H:%M:%S", required=False)

    class Meta:
        model = PointRecord
        fields = ['id', 'create_time', 'remain_point', 'point', 'operate_type', 'title', 'order_id']

    def get_title(self, obj):
        try:
            if obj.business_type == 1:
                return obj.activity_data.activity.name
            elif obj.business_type == 2:
                return obj.order.order_id
            else:
                return ''
        except:
            return ''

    def get_point(self, obj):
        try:
            point = str(int(obj.point))
            if len(point) >= 3:
                point = f'{point[:-2]},{point[-2:]}'
            if obj.operate_type == 2:
                point = '-' + point
            else:
                point = '+' + point
            return point
        except:
            return '0'

    def get_remain_point(self, obj):
        try:
            remain_point = str(int(obj.remain_point))
            if len(remain_point) >= 3:
                return f'{remain_point[:-2]},{remain_point[-2:]}'
            else:
                return remain_point
        except:
            return '0'


class ActivityDataRetrieveModelSerializer(serializers.ModelSerializer):

    point = serializers.SerializerMethodField(read_only=True)
    remain_point = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    available_time = serializers.SerializerMethodField(read_only=True)
    pointrecord_set = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ActivityData
        fields = ['id', 'point', 'activity_name', 'available_time', 'remain_point', 'pointrecord_set']

    def get_pointrecord_set(self, obj):
        try:
            pointrecord_set = obj.pointrecord_set.all().order_by('-id')
            return PointRecordModelSerializer(pointrecord_set, many=True).data
        except:
            return []

    def get_point(self, obj):
        try:
            point = str(int(obj.point))
            if len(point) >= 3:
                return f'{point[:-2]},{point[-2:]}'
            else:
                return point
        except:
            return '0'

    def get_remain_point(self, obj):
        try:
            remain_point = str(int(obj.remain_point))
            if len(remain_point) >= 3:
                return f'{remain_point[:-2]},{remain_point[-2:]}'
            else:
                return remain_point
        except:
            return '0'

    def get_activity_name(self, obj):
        try:
            return obj.activity.name
        except:
            return ''

    def get_available_time(self, obj):
        try:
            activity = obj.activity
            return f'{activity.available_end_time.strftime("%Y/%m/%d %H:%M:%S")}'
        except:
            return ''


class CashActivityDataListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityData
        fields = ['id', 'create_time', 'state_str', 'state', 'amount', 'activity_name']

    def get_activity_name(self, obj):
        try:
            return obj.cash_activity.name
        except:
            return ''


class CashActivityDataRetrieveModelSerializer(serializers.ModelSerializer):

    activity_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityData
        fields = ['id', 'amount', 'activity_name', 'available_time']

    def get_activity_name(self, obj):
        try:
            return obj.activity.name
        except:
            return ''


class CustomizeActivityFlipCARDSListModelSerializer(serializers.ModelSerializer):

    open_status_str = serializers.CharField(source='get_open_status_display', read_only=True)
    result = serializers.SerializerMethodField(read_only=True)
    coupon_data = serializers.SerializerMethodField(read_only=True)
    activity = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityFlipCARDS
        fields = ['id', 'open_status', 'open_status_str', 'result', 'return_msg', 'coupon_data', 'activity']

    def get_coupon_data(self, obj):
        coupon_data = []
        if obj.win_type == 8:
            customizeactivityrules_set = CustomizeActivityRules.objects.filter(customizeactivity_id=obj.customizeactivity_id)
            for customizeactivityrules in customizeactivityrules_set:
                rules_data = {}
                rules_data['floor_amount'] = customizeactivityrules.alidiscountcoupon.floor_amount
                rules_data['coupon_channel'] = customizeactivityrules.alidiscountcoupon.coupon_channel
                rules_data['count'] = customizeactivityrules.count
                coupon_data.append(rules_data)
        return coupon_data

    def get_result(self, obj):
        data = {}
        try:
            if obj.open_status == 1:
                return {}
            if obj.win_type == 4:
                data['amount'] = ''
                data['msg'] = ''
                data['win_type'] = obj.win_type
                data['win_type_str'] = obj.get_win_type_display()
                data['activity_name'] = ''
                data['available_time'] = ''
                return data
            elif obj.win_type in [3, 6]:
                cashactivity = obj.cashactivity
                data['amount'] = obj.amount
                data['msg'] = ''
                data['win_type'] = obj.win_type
                data['win_type_str'] = obj.get_win_type_display()
                data['activity_name'] = obj.cashactivity.name
                data['available_time'] = f'{cashactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{cashactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}'
                return data
            else:
                alidiscountcoupon = obj.alidiscountcoupon
                if alidiscountcoupon.coupon_type == 6:
                    data['amount'] = '单品券'
                else:
                    data['amount'] = alidiscountcoupon.amount
                data['msg'] = alidiscountcoupon.floor_amount
                data['win_type'] = obj.win_type
                data['win_type_str'] = obj.get_win_type_display()
                # data['name'] = alidiscountcoupon.activity_name
                data['activity_name'] = alidiscountcoupon.activity_name
                data['coupon_type'] = alidiscountcoupon.coupon_type
                data['available_time'] = f'{alidiscountcoupon.publish_start_time.strftime("%Y.%m.%d %H:%M:%S")}-{alidiscountcoupon.publish_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
                try:
                    data['voucher_id'] = obj.alidiscountcouponinfo.voucher_id
                except:
                    pass
                return data
        except:
            return data

    def get_activity(self, obj):
        data = {}
        try:
            customizeactivity = obj.customizeactivity
            data['activity_name'] = customizeactivity.activity_name
            data['available_begin_time'] = customizeactivity.available_begin_time.strftime("%Y-%m-%d %H:%M:%S")
            data['available_end_time'] = customizeactivity.available_end_time.strftime("%Y-%m-%d %H:%M:%S")
            data['is_need_auth'] = customizeactivity.is_need_auth
            data['is_psbc_card'] = customizeactivity.is_psbc_card
            if obj.open_status == 2 and customizeactivity.available_end_time < datetime.datetime.now():
                obj.open_status = 5
                obj.save()
        except:
            pass
        return data


class CustomizeActivityFlipCARDSRetrieveModelSerializer(serializers.ModelSerializer):

    open_status_str = serializers.CharField(source='get_open_status_display', read_only=True)
    result = serializers.SerializerMethodField(read_only=True)
    coupon_data = serializers.SerializerMethodField(read_only=True)
    activity = serializers.SerializerMethodField(read_only=True)
    coupon_detail = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityFlipCARDS
        fields = ['id', 'open_status', 'open_status_str', 'result', 'return_msg', 'coupon_data', 'activity', 'coupon_detail']

    def get_result(self, obj):
        data = {}
        try:
            if obj.open_status == 1:
                return {}
            if obj.win_type == 4:
                data['amount'] = ''
                data['msg'] = ''
                data['win_type'] = obj.win_type
                data['win_type_str'] = obj.get_win_type_display()
                data['activity_name'] = ''
                return data
            elif obj.win_type in [3, 6]:
                data['amount'] = obj.amount
                data['msg'] = ''
                data['win_type'] = obj.win_type
                data['win_type_str'] = obj.get_win_type_display()
                data['activity_name'] = obj.cashactivity.name
                return data
            else:
                alidiscountcoupon = obj.alidiscountcoupon
                if alidiscountcoupon.coupon_type == 6:
                    data['amount'] = '单品券'
                else:
                    data['amount'] = alidiscountcoupon.amount
                data['msg'] = alidiscountcoupon.floor_amount
                data['win_type'] = obj.win_type
                data['win_type_str'] = obj.get_win_type_display()
                # data['name'] = alidiscountcoupon.activity_name
                data['activity_name'] = alidiscountcoupon.activity_name
                data['coupon_type'] = alidiscountcoupon.coupon_type
                try:
                    data['voucher_id'] = obj.alidiscountcouponinfo.voucher_id
                except:
                    pass
                return data
        except:
            pass
        return data

    def get_activity(self, obj):
        data = {}
        try:
            customizeactivity = obj.customizeactivity
            data['activity_name'] = customizeactivity.activity_name
            data['available_begin_time'] = customizeactivity.available_begin_time.strftime("%Y-%m-%d %H:%M:%S")
            data['available_end_time'] = customizeactivity.available_end_time.strftime("%Y-%m-%d %H:%M:%S")
            data['is_need_auth'] = customizeactivity.is_need_auth
            data['is_psbc_card'] = customizeactivity.is_psbc_card
        except:
            pass
        return data

    def get_coupon_data(self, obj):
        coupon_data = []
        if obj.win_type == 8:
            customizeactivityrules_set = CustomizeActivityRules.objects.filter(customizeactivity_id=obj.customizeactivity_id)
            for customizeactivityrules in customizeactivityrules_set:
                rules_data = {}
                rules_data['floor_amount'] = customizeactivityrules.alidiscountcoupon.floor_amount
                rules_data['coupon_channel'] = customizeactivityrules.alidiscountcoupon.coupon_channel
                rules_data['count'] = customizeactivityrules.count
                coupon_data.append(rules_data)
        return coupon_data

    def get_coupon_detail(self, obj):
        try:
            queryset = AliDiscountCouponInfo.objects.filter(customizeactivityflipcardsdetail__flipcard_id=obj.id)
            return AliDiscountCouponInfoListModelSerializer(queryset, many=True).data
        except:
            return []


class CustomizeActivityRulesListModelSerializer(serializers.ModelSerializer):

    # prize_type_str = serializers.CharField(source='get_prize_type_display', read_only=True)
    prize_type_str = serializers.SerializerMethodField(read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)
    is_new_logo = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityRules
        fields = ['id', 'prize_type', 'prize_type_str', 'activity_info', 'is_new_logo']

    def get_prize_type_str(self, obj):
        try:
            if obj.customizeactivity_id in [100, 101, 132, 142]:
                return obj.cashactivity.name
            elif obj.customizeactivity_id in [136]:
                return obj.alidiscountcoupon.activity_name
            else:
                return obj.get_prize_type_display()
        except:
            return obj.get_prize_type_display()

    def get_is_new_logo(self, obj):
        try:
            if obj.customizeactivity_id in [100, 101]:
                return 1
            else:
                return 0
        except:
            return 0

    def get_activity_info(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['activity_id'] = ''
        data['rule'] = ''
        data['available_begin_time'] = ''
        data['available_end_time'] = ''
        data['amount'] = ''
        try:
            prize_type = obj.prize_type
            if prize_type in [1, 2, 7]:
                alidiscountcoupon = obj.alidiscountcoupon
                data['id'] = alidiscountcoupon.id
                data['activity_name'] = alidiscountcoupon.activity_name
                data['activity_id'] = alidiscountcoupon.template_id
                data['rule'] = alidiscountcoupon.floor_amount
                data['available_begin_time'] = alidiscountcoupon.publish_start_time.strftime("%Y-%m-%d %H:%M:%S")
                data['available_end_time'] = alidiscountcoupon.publish_end_time.strftime("%Y-%m-%d %H:%M:%S")
                if alidiscountcoupon.coupon_type == 6:
                    data['amount'] = '单品券'
                else:
                    data['amount'] = alidiscountcoupon.amount
                data['coupon_type'] = alidiscountcoupon.coupon_type
            elif prize_type in [3, 6]:
                cashactivity = obj.cashactivity
                cashactivityrule_set = cashactivity.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'¥{cashactivityrule.amount},'
                data['id'] = cashactivity.id
                data['activity_name'] = cashactivity.name
                data['activity_id'] = cashactivity.activity_id
                data['rule'] = result[:-1]
                data['available_begin_time'] = cashactivity.available_begin_time.strftime("%Y-%m-%d %H:%M:%S")
                data['available_end_time'] = cashactivity.available_end_time.strftime("%Y-%m-%d %H:%M:%S")
                data['amount'] = result[:-1]
        except:
            pass
        return data
